const fs = require('fs')
const path = require('path')
const shell = require('shelljs')
const format = require('util').format
const config = require('./config')
const Heatmap = require('./heatmap')
const utils = require('./utils')
const Repository = require('./repository')

const CANVAS_WIDTH = 1000
const CANVAS_HEIGHT = 1000
const HEAT_MAP_RADIUS = 50
const STATE_FILE = path.join(config.stateDir, 'state.json')
const HEAT_MAP_BMP = path.join(config.dataDir, 'heat.bmp')
const HEAT_MAP_PNG = path.join(config.dataDir, 'heat.png')

let lastSize = 0
let repo

async function refreshHeatMap() {
  console.log('enter refreshHeatMap')
  const allPixels = await repo.getAllPixels()
  const size = allPixels.length
  console.log('all pixels:', size)
  if (size === lastSize) {
    console.log('pixels not updated')
    return
  }
  lastSize = size
  let hm = new Heatmap({
    width: CANVAS_WIDTH,
    height: CANVAS_HEIGHT,
    radius: HEAT_MAP_RADIUS,
  })
  for (let p of allPixels) {
    const coordinate = p.coordinate
    const x = coordinate % CANVAS_WIDTH
    const y = (coordinate - x) / CANVAS_WIDTH
    const weight = Math.sqrt(p.seq / size)
    hm.addPoint(x, y, weight)
  }
  hm.save(HEAT_MAP_BMP)
  const cmd = format('convert %s %s', HEAT_MAP_BMP, HEAT_MAP_PNG)
  shell.exec(cmd)
  console.log('exit refreshHeatMap')
}

async function main() {
  repo = new Repository({ dir: config.stateDir })
  utils.loopAsync(refreshHeatMap, 60 * 1000)
}

main().then().catch(console.log)
